package com.atguigu.gulimall.order.interceptor;

import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.exception.RRException;
import com.atguigu.common.utils.JwtUtils;
import com.atguigu.common.vo.LoginUserVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginUserInterceptor implements HandlerInterceptor {

    public static ThreadLocal<LoginUserVo> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        LoginUserVo loginUser = JwtUtils.getUser(request, AuthServerConstant.LOGIN_USER);
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            throw new RRException(BizCodeEnum.COMMON_NO_TOKEN_EXCEPTION);
        }

        boolean checkToken = JwtUtils.checkToken(token);
        if (!checkToken)
            throw new RRException(BizCodeEnum.COMMON_TO_LOGIN_EXCEPTION);
        else
            threadLocal.set(loginUser);
        return true;
    }
}
